<template>
  <div>
    <MyTable :arr="arr">
        <!-- th插槽填充模板 -->
        <template #th>
            <th>#</th>
            <th>商品名称</th>
            <th>价格</th>
            <th>标签</th>
            <th>操作</th>
        </template>
        <!-- td插槽填充模板 -->
        <!-- 作用域插槽解构取值 -->
        <template #td="{row}">
            <td>{{row.id}}</td>
            <td>{{row.goods_name}}</td>
            <td>{{row.goods_price}}</td>
            <td>
                <!-- 自定义指令，v-focus 获取焦点 -->
                <input type="text" size="4"
                    v-if="row.inputVisible"
                    @blur="row.inputVisible = false"
                    @keydown.enter="keyEnter(row)"
                    v-model="row.inputValue"
                    v-focus
                >
                <button type="button" class="btn btn-primary btn-sm"
                    v-else
                    @click="row.inputVisible = true"
                >+Tag</button>
                <span v-for="(tag, index) in row.tags" :key="index" class="badge bg-warning text-dark">{{tag}}</span>
            </td>
            <td>
                <button class="btn btn-danger btn-sm" @click="del(row.id)">删除</button>
            </td>
        </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from '../components/MyTable'
export default {
  props: ['arr'],
  components: {
    MyTable
  },
  methods: {
    // 回车时
    keyEnter (row) {
      if (row.inputValue.trim() === '') return alert('填写标签')
      row.tags.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
    },
    // 删除
    del (id) {
      const index = this.arr.findIndex(el => el.id === id)
      this.arr.splice(index, 1)
    }
  },
  // 自定义指令，v-focus 获取焦点
  directives: {
    focus: {
      inserted (el, binding) {
        el.focus()
      }
    }
  }
}
</script>

<style>

</style>
